const api = require('../../utils/api.js');
const tools = require('../../utils/getuserinfo.js');
const internal = require('../../utils/international.js');
const app = getApp();
const { module: moduleName } = app.siteInfo;
const util = app.util;

Page({
  data: {
    cid: 0,
    page: 1,
    list: [],
    more: true,
    page_count: 1,
    longitude: '',
    latitude: '',
    score: [1, 2, 3, 4, 5],
    keyword: '',
    theme: app.themeData,
    cat: [],
    abnorData: {
      imgSrc: app.imgUrl + 'abnor-19.png',
      text: '本区域暂无门店入驻',
    },
    useTabbar: !(app.tabbarindex === 0 && app.siteInfo.tabbar_type === '1'),
    isShowLoading: false,
    imgUrl: app.imgUrl,
    multiIndex: [],
    isAllShow: false,
    isPlatShow: internal.getOrderStatus('isPlatShow'),
    version_type: app.ws_micro_shop_globalData.version_type,
    isSingle: app.ws_micro_shop_globalData.isSingle,
    shopinfo: null,
  },

  onLoad(opts) {
    let _this = this;

    let options = opts || {};
    if (options && options.shopid) {
      app.ws_micro_shop_globalData.shopid = options.shopid;
    }

    let store = wx.getStorageSync('store');

    this.setData({
      shopinfo: opts.shopinfo && JSON.parse(decodeURIComponent(opts.shopinfo)),
      store,
      cid: options.category || 0,
    });

    _this.getPrivice();
    _this.getList();

    let user_id = options.user_id;
    let share_scene = 4;
    app.tabbarindex = options.tabbarindex
      ? options.tabbarindex - 0
      : app.tabbarindex;
    // _this.loadShopCate();
    let userinfo = wx.getStorageSync('user_info');
    user_id && (app.ws_micro_shop_globalData.parent_id = user_id);
    if (userinfo) {
      Number(userinfo.info) === 0 && tools.onGetInfo(this, userinfo.auth_mode);
      app.loginBindParent({
        parent_id: user_id,
        shop_id: options.shopid,
        share_scene,
      });
      util.prepareBindInfo(options, moduleName, _this);
    } else {
      app.ws_micro_shoplogin().then(res => {
        userinfo = wx.getStorageSync('user_info');
        Number(userinfo.info) === 0 &&
          tools.onGetInfo(_this, userinfo.auth_mode);
        util.prepareBindInfo(options, moduleName, _this);
        app.getStoreData().then(res => {
          app.loginBindParent({
            parent_id: user_id,
            shop_id: options.shopid,
            share_scene,
          });
        });
      });
    }

    _this.setData({
      opts: options,
      useTabbar: _this.data.useTabbar && app.getTabBarStatus(),
    });
    
    app.pageOnLoad(this);
    
  },
  onShow() {

  },
  getList() {
    let _this = this;
    wx.getSetting({
      success(res) {
        if (typeof res.authSetting['scope.userLocation'] === 'undefined') {
          wx.getLocation({
            success: function (res) {
              _this.setData({
                latitude: res.latitude,
                longitude: res.longitude,
              });
              _this.autoLocation(res);
            },
            fail: function () {
              wx.navigateBack();
            },
          });
        } else if (res.authSetting['scope.userLocation'] === false) {
          _this.setData({
            open_setting: true,
          });
        } else {
          wx.getLocation({
            success: function (res) {
              _this.setData({
                latitude: res.latitude,
                longitude: res.longitude,
              });
              _this.autoLocation(res);
            },
          });
        }
      },
    });
  },
  getPrivice() {
    let that = this;
    app.ws_micro_shoprequest({
      url: api.default.province_city,
      success: function(res) {
        if (res.code === 0) {
          let { province = [], city = [] } = res.data;
          that.setData({
            multiArray: [province, city[0]],
            province,
            city,
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
          });
        }
      },
    });
  },
  bindMultiPickerColumnChange: function(e) {
    //e.detail.column 改变的数组下标列, e.detail.value 改变对应列的值
    console.log(e);
    console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    let { multiArray, multiIndex, province, city } = this.data;
    let data = {
      multiArray,
      multiIndex,
    };
    
    data.multiIndex[e.detail.column] = e.detail.value;
    switch (e.detail.column) {
      case 0:
        data.multiArray = [province, city[e.detail.value]];
        data.multiIndex[1] = 0;
        break;
    }
    this.setData(data);
  },

  bindMultiPickerChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value);
    let { multiArray, multiIndex, province, city } = this.data;
    multiIndex = e.detail.value;
    let value = [multiArray[0][multiIndex[0]], multiArray[1][multiIndex[1]]];
    value.length > 0 && (value = value.map(v => (v === '全部' ? '' : v))); // “全部”改为传空值
    value.every(v => v === '') && (value = ''); // 都是空值，传一个空值。
    let choosedLocation = value;
    let choosedArea = !value
      ? '全国'
      : value.filter(v => v !== '').reverse()[0];
    this.setData({ choosedLocation, choosedArea, isShowLoading: false }, () => {
      this.search();
    });
    this.setData({
      multiIndex: e.detail.value,
    });
  },

  loadShopCate() {
    let that = this;
    app.ws_micro_shoprequest({
      url: api.default.storecate,
      success: function(res) {
        if (res.code === 0) {
          let id = that.data.opts.category || 0;
          let { list, store_info } = res.data;
          for (let k in list) {
            if (Number(list[k].id) === Number(id)) {
              wx.setNavigationBarTitle({
                title: list[k].name,
              });
            }
          }
          that.setData({
            cat: list,
            storeInfo: store_info,
          });
        } else {
          wx.showToast({
            title: res.msg || '暂无分类',
            icon: 'none',
          });
        }
      },
    });
  },

  mobile() {
    wx.makePhoneCall({
      phoneNumber: this.data.shopinfo.mobile,
    });
  },

  goto() {
    let that = this;
    wx.getSetting({
      success(res) {
        if (typeof res.authSetting['scope.userLocation'] === 'undefined') {
          that.location();
        } else if (res.authSetting['scope.userLocation'] === false) {
          that.setData({
            open_setting: true,
          });
        } else {
          that.location();
        }
      },
    });
  },

  location() {
    let shop = this.data.shopinfo;
    wx.openLocation({
      latitude: parseFloat(shop.latitude),
      longitude: parseFloat(shop.longitude),
      name: shop.name,
      address: shop.address,
    });
  },

  switchNav(e) {
    let id = Number(e.currentTarget.dataset.id);
    let name = e.currentTarget.dataset.name;
    let cid = 0;
    if (cid === id && id !== 0) return;
    cid = id;
    this.setData({
      cid: cid,
      page: 1,
      list: [],
      more: true,
      isShowLoading: false,
    });
    wx.setNavigationBarTitle({
      title: name,
    });
    this.loadData(cid);
  },

  loadData(cid = 0) {
    let _this = this;
    let {
      longitude,
      latitude,
      list,
      page,
      more,
      keyword,
      choosedLocation: address = '',
    } = _this.data;
    if (more) {
      wx.showLoading({
        title: '加载中',
        mask: true,
      });
      app.ws_micro_shoprequest({
        url: api.default.shop_list,
        method: 'GET',
        data: {
          page,
          keyword,
          longitude,
          latitude,
          category: cid,
          address,
          sort: 1,
        },
        success: function(res) {
          wx.hideLoading();
          if (res.code === 0) {
            let newlist = res.data.list;
            if (newlist.length > 0) {
              page += 1;
              _this.setData({
                list: list.concat(newlist),
                page,
              });
            } else {
              _this.setData({
                more: false,
              });
              // wx.showToast({
              //   title: '没有更多数据了',
              //   icon: 'none',
              // });
            }
            // address &&
            //   _this.data.list.length === 0 &&
            //   _this.setData(
            //     { choosedLocation: '', choosedArea: '全国' },
            //     () => {
            //       _this.search();
            //     }
            //   );
          } else {
            wx.showToast({
              title: res.msg || '',
              icon: 'none',
            });
          }
          _this.setData({
            isShowLoading: true,
          });
        },
        complete: function () {
          _this.setData({
            isAllShow: true,
          });
        },
      });
    }
  },

  onPullDownRefresh() {
    let _this = this;
    _this.setData({
      keyword: '',
      page: 1,
      list: [],
      more: true,
      isShowLoading: false,
    });
    wx.getSetting({
      success(res) {
        if (typeof res.authSetting['scope.userLocation'] === 'undefined') {
          wx.getLocation({
            success: function(res) {
              _this.setData({
                latitude: res.latitude,
                longitude: res.longitude,
              });
              _this.loadData(_this.data.opts.category);
              wx.stopPullDownRefresh();
            },
            fail: function() {
              wx.navigateBack();
            },
          });
        } else if (res.authSetting['scope.userLocation'] === false) {
          _this.setData({
            open_setting: true,
          });
        } else {
          wx.getLocation({
            success: function(res) {
              _this.setData({
                latitude: res.latitude,
                longitude: res.longitude,
              });
              _this.loadData(_this.data.opts.category);
              wx.stopPullDownRefresh();
            },
          });
        }
      },
    });
  },

  onReachBottom() {
    this.loadData(this.data.cid);
  },

  inputFocus() {
    this.setData({
      show: true,
    });
  },

  inputBlur() {
    this.setData({
      show: false,
    });
  },

  inputConfirm() {
    this.search();
  },

  input(e) {
    this.setData({
      keyword: e.detail.value,
    });
  },

  search() {
    this.setData({
      page: 1,
      more: true,
      list: [],
      isShowLoading: false,
    });
    this.loadData(this.data.cid);
  },

  go(e) {
    let index = e.currentTarget.dataset.index;
    let shop_list = this.data.list;
    wx.navigateTo({
      url:
        '/ws_micro_shop/pages/shop-detail/shop-detail?shop_id=' +
        shop_list[index].id,
    });
  },

  goback() {
    wx.removeStorageSync('latestShopId');
    app.ws_micro_shop_globalData.shopid = 0;
    wx.reLaunch({
      url: '/ws_micro_shop/pages/home/index?visit_platform=1',
    });
  },

  change(e) {
    app.ws_micro_shop_globalData.shopid = e.currentTarget.dataset.id;
    wx.setStorageSync('latestShopId', e.currentTarget.dataset.id);
    wx.setStorageSync('is_on_show', true);
    util.navigateTo('/ws_micro_shop/pages/index/index');
  },

  onShareAppMessage() {
    let user_info = wx.getStorageSync('user_info');
    let path =
      '/ws_micro_shop/pages/shop/shop?user_id=' +
      user_info.id +
      '&tabbarindex=' +
      app.tabbarindex +
      '&shopid=' +
      app.ws_micro_shop_globalData.shopid;
    path = util.spliceSharePath(path, '4', moduleName);
    return {
      path,
    };
  },

  onShareTimeline() {
    let user_info = wx.getStorageSync('user_info');
    return {
      title: '',
      imageUrl: '',
      query: 'user_id=' +
      user_info.id +
      '&tabbarindex=' +
      app.tabbarindex +
      '&shopid=' +
      app.ws_micro_shop_globalData.shopid,
    }
  },

  onHide() {
    util.sendBindInfo(this.data);
  },

  onUnload() {
    util.sendBindInfo(this.data);
  },

  collectFormId(e) {
    app.collectFormId(e);
  },

  autoLocation(e) {
    // app.ws_micro_shoprequest({
    //   url: api.default.coornate,
    //   data: {
    //     longitude: e.longitude,
    //     latitude: e.latitude,
    //   },
    //   success: res => {
    //     if (res.code === 0) {
    //       if (res.data && res.data.coornate) {
    //         let coornate = res.data.coornate;
    //         let choosedLocation = [
    //           coornate.province,
    //           coornate.city,
    //         ];
    //         let choosedArea = coornate.city;
    //         this.setData({ choosedLocation, choosedArea }, () => {
    //           this.search();
    //         });
    //       }
    //     }
    //   },
    // });
    let choosedLocation = '';
    let choosedArea = '全国';
    this.setData({ choosedLocation, choosedArea }, () => {
      this.search();
    });
  },

  onChooseLocation(e) {
    let { value = [] } = e.detail;
    value.length > 0 && (value = value.map(v => (v === '全部' ? '' : v))); // “全部”改为传空值
    value.every(v => v === '') && (value = ''); // 都是空值，传一个空值。
    let choosedLocation = value;
    let choosedArea = !value
      ? '全国'
      : value.filter(v => v !== '').reverse()[0];
    this.setData({ choosedLocation, choosedArea, isShowLoading: false }, () => {
      this.search();
    });
  },
});
